package com.sicpa.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.sicpa.common.core.domain.VdsPk7DetachParam;
import com.sicpa.common.utils.HttpUtil;
import com.sicpa.common.utils.JsonUtil;
import com.sicpa.common.utils.SignUtils;
import com.sicpa.common.utils.StringUtils;
import com.sicpa.system.service.ICaAuthServcie;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * CaAuthServcieImpl
 *
 * @author lwf
 */
@Service
public class CaAuthServcieImpl implements ICaAuthServcie {

    @Value("${ca.url}")
    private String caUrl;

    @Value("${ca.application.code}")
    private String applicationCode;

    @Value("${ca.application.secret}")
    private String applicationSecret;

    @Value("${ca.application.visitor}")
    private String applicationVisitor;


    /**
     * CA 验证签名
     *
     * @param signData
     * @return
     */
    @Override
    public boolean caVerifySignature(String signData) {
        String getCheckParam = getCheckParam(signData);
        ObjectNode node = JsonUtil.readValue(getCheckParam, ObjectNode.class);
        ObjectNode signedParam = SignUtils.getParam(node, applicationSecret);
        String response = HttpUtil.sendDataByPost(caUrl + "/svs/api/svs/verifySignDataPkcs7", signedParam.toString());
        if (StringUtils.isNotEmpty(response)) {
            JSONObject caRes = JSON.parseObject(response);
            Integer returnCode = caRes.getInteger("returnCode");
            return returnCode == 1;
        }
        return false;
    }

    /**
     * 封装验签请求参数
     *
     * @return
     */
    private String getCheckParam(String signData) {
        VdsPk7DetachParam param = new VdsPk7DetachParam();
        param.setApplicationCode(applicationCode);
        param.setInitData(signData);
        param.setInitDataType(applicationSecret);
        param.setInitDataType("0");
        return JSON.toJSONString(param);
    }
}
